"""活动中心视图
处理社团、活动、报名等相关的API请求
"""

from rest_framework import status, generics, permissions, filters
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.db.models import Count, F
from django.shortcuts import get_object_or_404
from rest_framework import permissions, status, generics
from django.db import transaction
from django.utils import timezone
from .models import Club, ClubMember, Activity, ActivityRegistration, ActivityImage
from .serializers import (
    ClubSerializer, ClubDetailSerializer, ClubMemberSerializer,
    ActivitySerializer, ActivityDetailSerializer, ActivityListSerializer, ActivityCreateSerializer,
    ActivityRegistrationSerializer, ActivityImageSerializer
)
from utils.response import success_response, error_response, paginated_response


class ClubListView(generics.ListAPIView):
    """
    社团列表视图
    """
    permission_classes = [permissions.AllowAny]
    serializer_class = ClubDetailSerializer
    queryset = Club.objects.filter(status='active')  # 移除is_verified=True条件，允许所有活跃社团显示
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['name', 'description', 'category']
    ordering_fields = ['member_count', 'founded_date']
    ordering = ['-member_count']

    def list(self, request, *args, **kwargs):
        """获取社团列表"""
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return success_response(
            data=serializer.data,
            message="获取社团列表成功"
        )


class ClubDetailView(generics.RetrieveAPIView):
    """
    社团详情视图
    """
    permission_classes = [permissions.AllowAny]
    serializer_class = ClubDetailSerializer
    queryset = Club.objects.filter(status='active', is_verified=True)

    def retrieve(self, request, *args, **kwargs):
        """获取社团详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(
            data=serializer.data,
            message="获取社团详情成功"
        )


class ActivityListView(generics.ListAPIView):
    """
    活动列表视图
    """
    permission_classes = [permissions.AllowAny]
    serializer_class = ActivityListSerializer
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['title', 'description']
    ordering_fields = ['created_at', 'start_time', 'participant_count']
    ordering = ['-created_at']

    def get_queryset(self):
        """获取活动列表"""
        # 不设置默认状态筛选，让前端通过status参数控制
        queryset = Activity.objects.all()

        # 社团筛选（如果有值则筛选，没有值则包含个人活动）
        club_id = self.request.query_params.get('club')
        if club_id:
            queryset = queryset.filter(club_id=club_id)
        # 个人活动筛选
        if self.request.query_params.get('personal') == 'true':
            queryset = queryset.filter(club__isnull=True)

        # 类型筛选
        activity_type = self.request.query_params.get('type')
        if activity_type:
            queryset = queryset.filter(activity_type=activity_type)

        # 状态筛选
        status = self.request.query_params.get('status')
        if status:
            # 特殊处理'已报满'状态
            if status == 'full':
                queryset = queryset.filter(
                    status='registration_open',
                    current_participants__gte=models.F('max_participants')
                )
            else:
                queryset = queryset.filter(status=status)

        return queryset

    def list(self, request, *args, **kwargs):
        """获取活动列表"""
        queryset = self.get_queryset()

        # 分页
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('page_size', 10))
        start = (page - 1) * page_size
        end = start + page_size

        total_count = queryset.count()
        activities = queryset[start:end]

        serializer = self.get_serializer(activities, many=True)
        return paginated_response(
            data=serializer.data,
            count=total_count,
            page=page,
            page_size=page_size
        )


class ActivityDetailView(generics.RetrieveAPIView):
    """
    活动详情视图
    """
    permission_classes = [permissions.AllowAny]
    serializer_class = ActivityDetailSerializer
    # 不设置默认状态筛选，允许查看所有状态的活动
    queryset = Activity.objects.all()

    def retrieve(self, request, *args, **kwargs):
        """获取活动详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(
            data=serializer.data,
            message="获取活动详情成功"
        )


class ActivityRegistrationView(generics.CreateAPIView):
    """
    活动报名视图
    """
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ActivityRegistrationSerializer

    def create(self, request, *args, **kwargs):
        """报名活动"""
        # 检查活动是否存在且可报名
        activity_id = request.data.get('activity')
        activity = get_object_or_404(Activity, id=activity_id)

        # 只允许registration_open状态的活动报名
        if activity.status != 'registration_open':
            return error_response(
                message="该活动未开放报名",
                status_code=status.HTTP_400_BAD_REQUEST
            )

        # 检查是否超过最大参与人数
        if activity.max_participants and activity.current_participants >= activity.max_participants:
            return error_response(
                message="该活动已达到最大参与人数",
                status_code=status.HTTP_400_BAD_REQUEST
            )

        # 检查是否已报名
        if ActivityRegistration.objects.filter(
            user=request.user,
            activity=activity
        ).exists():
            return error_response(
                message="您已报名该活动",
                status_code=status.HTTP_400_BAD_REQUEST
            )

        # 创建报名记录
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            try:
                with transaction.atomic():
                    registration = serializer.save(user=request.user)
                    # 更新活动参与人数
                    activity.current_participants += 1
                    activity.save()
                    return Response({
                        'code': 201,
                        'message': "报名成功",
                        'data': ActivityRegistrationSerializer(registration, context={'request': request}).data,
                        'success': True
                    }, status=status.HTTP_201_CREATED)
            except Exception as e:
                return error_response(
                    message=f"报名失败: {str(e)}",
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        else:
            return error_response(
                message=f"报名失败: {serializer.errors}",
                status_code=status.HTTP_400_BAD_REQUEST
            )


class CreateClubView(generics.CreateAPIView):
    """
    创建社团视图
    允许已登录用户创建新社团
    """
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ClubSerializer

    def create(self, request, *args, **kwargs):
        """创建新社团"""
        # 允许一个用户创建多个社团
        

        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            try:
                with transaction.atomic():
                    # 创建社团
                    club = serializer.save(
                        founded_date=timezone.now().date(),
                        is_verified=False  # 新创建的社团需要审核
                    )
                    # 手动设置成员数量，因为在序列化器中这是只读字段
                    club.member_count = 1
                    club.save()
                    
                    # 创建者自动成为会长
                    ClubMember.objects.create(
                        club=club,
                        user=request.user,
                        role='president'
                    )
                    
                    return success_response(
                        data=ClubDetailSerializer(club, context={'request': request}).data,
                        message="社团创建成功，等待审核",
                        code=201
                    )
            except Exception as e:
                return error_response(
                    message=f"社团创建失败: {str(e)}",
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        else:
            return error_response(
                message=f"社团创建失败: {serializer.errors}",
                status_code=status.HTTP_400_BAD_REQUEST
            )


class UserClubsView(generics.ListAPIView):
    """
    用户社团列表视图
    获取当前登录用户加入的所有社团
    """
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ClubDetailSerializer

    def get_queryset(self):
        """获取用户加入的社团列表"""
        # 获取当前用户加入的所有社团
        user_clubs = Club.objects.filter(
            members__user=self.request.user,
            members__is_active=True
        ).order_by('-created_at')
        return user_clubs

    def list(self, request, *args, **kwargs):
        """返回用户社团列表"""
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return success_response(
            data=serializer.data,
            message="获取用户社团列表成功"
        )


class CreateActivityView(generics.CreateAPIView):
    """
    创建活动视图
    允许用户创建个人活动或作为社团负责人创建社团活动
    """
    permission_classes = [permissions.IsAuthenticated]
    serializer_class = ActivityCreateSerializer

    def create(self, request, *args, **kwargs):
        """创建新活动"""
        # 获取活动类型（个人活动或社团活动）
        activity_type = request.data.get('activity_creation_type', 'personal')  # 默认为个人活动
        club_id = request.data.get('club')
        
        # 检查社团活动的权限
        if activity_type == 'club':
            if not club_id:
                return error_response(
                    message="创建社团活动请选择所属社团",
                    status_code=status.HTTP_400_BAD_REQUEST
                )

            club = get_object_or_404(Club, id=club_id)
            
            # 检查用户是否是该社团的创建人或负责人
            # 只有社团创建人才能发布社团活动
            club_creator = ClubMember.objects.filter(
                club=club,
                user=request.user,
                role='president',  # 只有会长可以发布活动
                is_active=True
            ).exists()

            if not club_creator:
                return error_response(
                    message="您不是该社团的创建人，无权以社团名义发布活动",
                    status_code=status.HTTP_403_FORBIDDEN
                )

        # 检查时间逻辑
        start_time = request.data.get('start_time')
        end_time = request.data.get('end_time')
        registration_deadline = request.data.get('registration_deadline')

        if start_time and end_time and start_time > end_time:
            return error_response(
                message="活动开始时间不能晚于结束时间",
                status_code=status.HTTP_400_BAD_REQUEST
            )

        if start_time and registration_deadline and registration_deadline > start_time:
            return error_response(
                message="报名截止时间不能晚于活动开始时间",
                status_code=status.HTTP_400_BAD_REQUEST
            )

        # 处理文件上传需要使用request.FILES
        data = request.data.copy()
        files = request.FILES.getlist('images') if 'images' in request.FILES else []
        
        serializer = self.get_serializer(data=data)
        if serializer.is_valid():
            try:
                with transaction.atomic():
                    activity = serializer.save(
                        organizer=request.user,
                        current_participants=0,  # 修正字段名
                        status='registration_open'  # 改为开放报名状态，而不是草稿状态
                    )
                    
                    # 处理上传的图片
                    for i, image_file in enumerate(files):
                        ActivityImage.objects.create(
                            activity=activity,
                            image=image_file,
                            order=i
                        )
                    
                    return success_response(
                        data=ActivityDetailSerializer(activity, context={'request': request}).data,
                        message="活动创建成功",
                        code=201
                    )
            except Exception as e:
                return error_response(
                    message=f"活动创建失败: {str(e)}",
                    status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
                )
        else:
            return error_response(
                message=f"活动创建失败: {serializer.errors}",
                status_code=status.HTTP_400_BAD_REQUEST
            )
